<?php
include '../dbconnect.php';

// 获取服务ID
$service_id = isset($_GET['gid']) ? $_GET['gid'] : '';
if (empty($service_id)) {
    echo "服务ID不能为空！";
    exit;
}

// 检查所有必要的POST变量是否已设置
if (!isset($_POST['SERVICE_NAME']) || !isset($_POST['SERVICE_TYPE']) || !isset($_POST['SERVICE_CONTENT'])) {
    echo "所有字段都是必填的！";
    exit;
}

// 获取服务信息
$SERVICE_NAME = $_POST['SERVICE_NAME'];
$SERVICE_TYPE = $_POST['SERVICE_TYPE'];
$SERVICE_CONTENT = $_POST['SERVICE_CONTENT'];

// 处理图片上传
if (isset($_FILES['SERVICE_PICTURE']) && $_FILES['SERVICE_PICTURE']['error'] == UPLOAD_ERR_OK) {
    $file = $_FILES['SERVICE_PICTURE'];
    $name = $file['name'];
    $ext = strtolower(substr($name, strrpos($name, '.') + 1)); // 得到文件类型，并转化为小写
    $allow_type = array('jpg', 'jpeg', 'gif', 'png'); // 定义允许上传的类型

    // 判断文件类型是否被允许上传
    if (!in_array($ext, $allow_type)) {
        echo "不允许的文件类型！";
        exit;
    }

    // 判断是否是通过HTTP POST上传的
    if (!is_uploaded_file($file['tmp_name'])) {
        echo "非法上传！";
        exit;
    }

    $currentDir = dirname(__FILE__);
    // 构建上传路径
    $upload_path = $currentDir . '/uploads/'; // 获取当前目录并添加uploads子目录

    // 确保uploads目录存在
    if (!is_dir($upload_path)) {
        mkdir($upload_path, 0777, true);
    }

    // 开始移动文件到相应的文件夹
    if (move_uploaded_file($file['tmp_name'], $upload_path . $name)) {
        $base_url = 'http://localhost/BWD_Assignment/employee/';
        $SERVICE_PICTURE = $base_url . 'uploads/' . $name;
    } else {
        echo "UPLOAD FAIL！";
        exit;
    }
} else {
    // 如果没有上传新图片，保持原来的图片路径
    $SERVICE_PICTURE = isset($_POST['old_SERVICE_PICTURE']) ? $_POST['old_SERVICE_PICTURE'] : '';
}

// 更新服务信息
$sql = "UPDATE services SET SERVICE_NAME = ?, SERVICE_TYPE = ?, SERVICE_CONTENT = ?, SERVICE_PICTURE = ? WHERE SERVICE_ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $SERVICE_NAME, $SERVICE_TYPE, $SERVICE_CONTENT, $SERVICE_PICTURE, $service_id);

if ($stmt->execute()) {
    echo "更新成功！";
    header("Location: serviceslist.php");
    exit;
} else {
    echo "更新失败：" . $stmt->error;
    exit;
}

$stmt->close();
$conn->close();
?>